using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Phone.Shell;
using Serialization;
using WindowsPhoneEssentials.Abstractions;

namespace WindowsPhoneEssentials.Storage
{
    public class TransientStore : ITransientStore 
    {
        private readonly IIsolatedStorageFileFactory isolatedStorageFileFactory;
        private readonly IPhoneApplicationService phoneApplicationService;
        private const string StoreKey = "WindowsPhoneEssentials.Storage.TransientStoreFiles";

        public TransientStore()
        {
            isolatedStorageFileFactory = new IsolatedStorageFileFactory();
        }

        public TransientStore(IIsolatedStorageFileFactory isolatedStorageFileFactory, IPhoneApplicationService phoneApplicationService)
        {
            this.isolatedStorageFileFactory = isolatedStorageFileFactory;
            this.phoneApplicationService = phoneApplicationService;
        }

        private IDictionary<string, object> PhoneState
        {
            get
            {
                return phoneApplicationService == null 
                    ? PhoneApplicationService.Current.State 
                    : phoneApplicationService.State;
            }
        }

        public void Save<T>(string key, T value) where T : class
        {
            using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
            {
                using (var stream = store.OpenFile(GetFileName(key), FileMode.Create))
                {
                    SilverlightSerializer.Serialize(value, stream);
                }
            }

            var state = PhoneState;
            if (state.ContainsKey(StoreKey))
            {
                var list = (List<string>)state[StoreKey];
                if (!list.Contains(key))
                    list.Add(key);
            }
            else
                state.Add(StoreKey, new List<string>{ key });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns>null if not found, otherwise saved value</returns>
        public T Load<T>(string key) where T : class
        {
            if (Contains(key))
            {
                using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
                {
                    using (var stream = store.OpenFile(GetFileName(key), FileMode.OpenOrCreate))
                    {
                        if (stream.Length > 0)
                        {
                            return SilverlightSerializer.Deserialize<T>(stream);
                        }
                    }
                }
            }

            return null;
        }

        public bool Contains(string key)
        {
            var state = PhoneState;
            return state.ContainsKey(StoreKey) && ((List<string>)state[StoreKey]).Contains(key);
        }

        public void Remove(string key)
        {
            var state = PhoneState;
            if (!state.ContainsKey(StoreKey)) return;

            var list = (List<string>)state[StoreKey];

            list.Remove(key);
            using (var store = isolatedStorageFileFactory.GetUserStoreForApplication())
            {
                foreach (var file in store.GetFileNames(GetFileName(key)))
                {
                    store.DeleteFile(file);
                }
            }
        }

        private static string GetFileName(string key)
        {
            return string.Format("{0}.{1}", StoreKey, key);
        }
    }
}